var lunboImgesUrl = "";
var imageUrlList = [[],[],[],[],[],[],[],[],[],[],[],[]];
var applyData;
var certifiedImgUrl;
var nowAuditState;

init();

function init() {
    queryApplyList();
}

function savePic(){
    var formData = new FormData($( "#uploadPic" )[0]);
    console.log($("#uploadPic")[0]);
    $.ajax({
        type: "POST",
        url: prefixUrl + "image/upload",
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            commodityThumbnail =  data;
            certifiedImgUrl = imageUrl + data;
            $("#image").attr("src",imageUrl + data);
        }
    });
}

function queryApplyList(pageIndex) {
    if (pageIndex == null) {
        pageIndex = 0;
    }
    var queryName = $("#queryName").val();
    var beginDate = $("#beginDate").val();
    var overDate = $("#overDate").val();
    $.ajax({
        url: prefixUrl + "apply/queryapply",
        type: "post",
        data: JSON.stringify({
            applyNo: queryName,
            applyName: queryName,
            beginDate: beginDate,
            overDate: overDate,
            pageIndex: pageIndex
        }),
        contentType: "application/json;",
        success: function (data) {
            goToLogin(data)
            var commonHtml = '<thead>'
                + '<tr>'
                + '<th>票据编号</th>'
                + '<th>票据名称</th>'
                + '<th>申请人</th>'
                + '<th>申请单位</th>'
                + '<th>申请时间</th>'
                + '<th>状态</th>'
                + '<th>操作</th>'
                + '</tr>'
                + '</thead>'
                + '<tbody>';
            var list = data.data.rows;

            for (var i = 0; i < list.length; i++) {
                commonHtml = commonHtml
                    + '<tr>'
                    + '<td>'
                    + list[i].applyNo
                    + '</td>'
                    + '<td>'
                    + list[i].applyName
                    + '</td>'
                    + '<td>'
                    + list[i].applyPerson
                    + '</td>'
                    + '<td>'
                    + list[i].applyCompanyName
                    + '</td>'
                    + '<td>'
                    + new Date(list[i].oprDate).toLocaleDateString()
                    + '</td>';

                var state;
                if (list[i].auditState == 0) {
                    state = "未审查";
                    commonHtml = commonHtml
                        + '<td><span style="color: #1e252f">'
                        + state
                        + '<span/></td>'
                } else if (list[i].auditState == 1) {
                    state = "退回修改";
                    commonHtml = commonHtml
                        + '<td><span style="color: gold">'
                        + state
                        + '<span/></td>'
                } else if (list[i].auditState == 2) {
                    state = "审查通过";
                    commonHtml = commonHtml
                        + '<td><span style="color: #2ecd71">'
                        + state
                        + '<span/></td>'
                } else if (list[i].auditState == 3){
                    state = "审查不通过";
                    commonHtml = commonHtml
                        + '<td><span style="color: red">'
                        + state
                        + '<span/></td>'
                }else if(list[i].auditState == null){
                    state = "待盖章";
                    commonHtml = commonHtml
                        + '<td><span style="color: #1e252f">'
                        + state
                        + '<span/></td>'
                }
                commonHtml = commonHtml
                    + '<td>'
                    + '<button type="button" class="btn btn-info mar-r-5" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" onclick=queryApplyDetail("'
                    + list[i].applyId
                    + '")><i class="fa fa-pencil"></i></button>';
                if(list[i].auditState == 2){
                    commonHtml = commonHtml
                        + '<button type="button" class="btn btn-info mar-r-5" data-toggle="modal" data-whatever="@mdo" onclick=exportAuditPdf("'
                        + list[i].applyId
                        + '","'
                        + list[i].certifiedImgUrl
                        + '") ><i class="fa fa-cloud-download"></i></button>';
                }else{
                    commonHtml = commonHtml
                        + '<button type="button" class="btn btn-info mar-r-5" data-toggle="modal" data-whatever="@mdo" onclick=exportPdf("'
                        + list[i].applyId
                        + '","'
                        + list[i].applyNo
                        + '") ><i class="fa fa-cloud-download"></i></button>';
                }
                commonHtml = commonHtml
                    + '</td>'
                    + '</tr>';
            }
            commonHtml = commonHtml + '</tbody>';
            $("#applyList").html(commonHtml);

            var total = data.data.total;
            var remainder = total % 20;
            var allNumber = 0;
            if (remainder > 0) {
                allNumber = parseInt(total / 20) + 1;
            } else {
                allNumber = parseInt(total / 20);
            }
            var number = 1;
            var numberHtml = '<li><a onclick=queryApplyList(' + "0" + ')>«</a></li>';
            for (var i = 0; i < allNumber; i++) {
                var id = "query-" + i;
                if (i == 0) {
                    numberHtml = numberHtml
                        + '<li id="' + id + '" name="queryList" class="active"><a onclick=queryApplyList(' + i + ')>' + number + '</a></li>';
                } else {
                    numberHtml = numberHtml
                        + '<li id="' + id + '" name="queryList"><a onclick=queryApplyList(' + i + ')>' + number + '</a></li>';
                }
                number++;
            }
            numberHtml = numberHtml + '<li><a onclick=queryApplyList(' + (allNumber - 1) + ')>»</a></li>';
            $("#queryList").html(numberHtml);
        }
    })
}

$("#queryName").change(function () {
    queryApplyList();
});
$("#beginDate").change(function () {
    queryApplyList();
});
$("#overDate").change(function () {
    queryApplyList();
});


function queryApplyDetail(id) {
    $.ajax({
        url: prefixUrl + "apply/qureysinple",
        type: "post",
        data: JSON.stringify({
            applyId: id
        }),
        contentType: "application/json;",
        success: function (data) {
            applyData = data.data;
            var detail = data.data;
            nowAuditState = detail.auditState;
            certifiedImgUrl = detail.certifiedImgUrl;

            $("#applyNo").val(detail.applyNo);
            $("#applyName").val(detail.applyName);
            $("#applyCompanyName").val(detail.applyCompanyName);
            $("#applyType").val(detail.applyType);
            $("#applyPerson").val(detail.applyPerson);
            $("#applyAddr").val(detail.applyAddr);
            $("#applyPhone").val(detail.applyPhone);
            $("#applyStreet").val(detail.applyStreet);
            $("#auditDesc").val(detail.auditDesc);
            if(detail.certifiedImgUrl == null || detail.certifiedImgUrl == ""){
                $("#image").attr("src","images/z_add.png");
            }else{
                $("#image").attr("src",detail.certifiedImgUrl);
            }

            $("#applyNo").attr("disabled", "disabled");
            if(detail.auditState == null){
                $("#submit").attr("disabled", false);
            }else{
                $("#submit").attr("disabled", "disabled");
            }
            if(detail.auditState == 2){
                $("#auditImg").attr("class","auditImgYes");
                $("#auditImg").show();
            }else if(detail.auditState == 1){
                $("#auditImg").attr("class","auditImgNo");
                $("#auditImg").show();
            }else{
                $("#auditImg").hide();
            }
            if (detail.auditState != 1) {
                $("#update").attr("disabled", "disabled");
                $("#applyName").attr("disabled", "disabled");
                $("#applyCompanyName").attr("disabled", "disabled");
                $("#applyType").attr("disabled", "disabled");
                $("#applyPerson").attr("disabled", "disabled");
                $("#applyAddr").attr("disabled", "disabled");
                $("#applyPhone").attr("disabled", "disabled");
                $("#applyStreet").attr("disabled", "disabled");
                $("#div").attr("disabled", "disabled");
                $("#file").attr("disabled", "disabled");
            } else {
                $("#update").attr("disabled", false);
                $("#applyName").attr("disabled", false);
                $("#applyCompanyName").attr("disabled", false);
                $("#applyType").attr("disabled", false);
                $("#applyPerson").attr("disabled", false);
                $("#applyAddr").attr("disabled", false);
                $("#applyPhone").attr("disabled", false);
                $("#applyStreet").attr("disabled", false);
                $("#div img").attr("disabled", false);
                $("#file").attr("disabled", false);
            }
            $("#auditDesc").attr("disabled", "disabled");
            if(detail.auditState > 0){
                $("#auditModel").show();
                $("#submit").show();
                $("#uploadAuditImg").show();
            }else{
                if(detail.auditState == 0){
                    $("#submit").hide();
                    $("#uploadAuditImg").hide();
                }else{
                    $("#submit").show();
                    $("#uploadAuditImg").show();
                }
                $("#auditModel").hide();
            }
            getImageUrlList(data.data.list);
            var detailList = getPageImageList(data.data.list);
            //轮播图回显
            if (detail.imgUrl != null && detail.imgUrl != "") {
                getLunBo(detailList,nowAuditState);
            }else{
                getLunBo("",nowAuditState);
            }
        }
    })
}

function updateApply() {
    if ($("#applyNo").val() == null || $("#applyNo").val() == "") {
        alert("票据编号不可为空");
        return;
    }
    if ($("#applyName").val() == null || $("#applyName").val() == "") {
        alert("票据名称不可为空");
        return;
    }
    if ($("#applyCompanyName").val() == null || $("#applyCompanyName").val() == "") {
        alert("单位名称不可为空");
        return;
    }
    if ($("#applyType").val() == 0) {
        alert("请选择审查类型");
        return;
    }
    if ($("#applyPerson").val() == null || $("#applyPerson").val() == "") {
        alert("单位联系人不可为空");
        return;
    }
    if ($("#applyAddr").val() == null || $("#applyAddr").val() == "") {
        alert("申请单位地址不可为空");
        return;
    }
    if ($("#applyPhone").val() == null || $("#applyAddr").val() == "") {
        alert("申请单位电话不可为空");
        return;
    }
    if($("#applyStreet").val() == null ||　$("#applyStreet").val() == "" || $("#applyStreet").val() == 0){
        alert("申请单位街道不可为空");
        return;
    }

    var applyDetailList = getDetailList(imageUrlList,applyData.applyId);
    var data = {
        applyId: applyData.applyId,
        applyNo: $("#applyNo").val(),
        applyName: $("#applyName").val(),
        applyCompanyName: $("#applyCompanyName").val(),
        applyType: $("#applyType").val(),
        applyPerson: $("#applyPerson").val(),
        applyAddr: $("#applyAddr").val(),
        applyPhone: $("#applyPhone").val(),
        applyStreet: $("#applyStreet").val(),
        certifiedImgUrl:certifiedImgUrl,
        imgUrl: lunboImgesUrl,
        detailList:applyDetailList
    };
    $.ajax({
        url: prefixUrl + "apply/update",
        type: "post",
        data: JSON.stringify(data),
        contentType: "application/json;",
        success: function (data) {
            alert(data.msg);
            modalDisplay();
            queryApplyList();
        }
    })
}

function deleteApply(id) {
    if (confirm("确定删除么？")) {
        $.ajax({
            url: prefixUrl + "apply/delete",
            type: "post",
            data: JSON.stringify({
                applyId: id
            }),
            contentType: "application/json;",
            success: function (data) {
                alert(data.msg);
                queryApplyList();
            }
        });
    }

}

function commitApply(applyId, applyNo) {
    $.ajax({
        url: prefixUrl + "audit/addaudit",
        type: "post",
        data: JSON.stringify({
            applyId: applyId,
            applyNo: applyNo,
            auditState: 0
        }),
        contentType: "application/json;",
        success: function (data) {
            if (data.code == 0) {
                alert("提交成功！请耐心等待");
                queryApplyList();
            } else {
                alert("提交失败！");
                queryApplyList();
            }

        }
    })

}


function excel() {
    $("#exportForm").submit();
}

function getLunBo(lunboImgUrl,nowAuditState) {
    lunboImgesUrl = lunboImgUrl;

    var lunboImgList = lunboImgUrl.split(",");
    var state = true;
    if(nowAuditState == 1){
        state = false;
    }
    if(lunboImgList.length > 0){
        lunboHtml = "";
        for (var i = 1; i < 13; i++) {
            lunboHtml = lunboHtml
                + '<section class="up-section fl">'
                + '<span class="up-span" onclick=choiceImg(' + i + ',' + state + ')></span>'
                + '<img id="img' + i + '"  class="up-img"  src="img/type-'
                + i
                + '.png"><input id="taglocation" name="taglocation" value="" type="hidden">'
                + '<input id="tags" name="tags" value="" type="hidden">'
                + '</section>';
        }
        $("#lunbo").html(lunboHtml);
    }

    addFileChange();
}

function addFileChange() {
    var delParent;
    var imagesUrl;
    var defaults = {
        fileType: ["jpg", "png", "bmp", "jpeg"],   // 上传文件的类型
        fileSize: 1024 * 1024 * 10                  // 上传文件的大小 10M
    };
    /*点击图片的文本框*/
    $(".file").change(function () {
        var idFile = $(this).attr("id");
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        var fileList = file.files; //获取的图片文件
        var input = $(this).parent();//文本框的父亲元素
        var imgArr = [];
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length;  //总的数量
        if (fileList.length > 15 || totalNum > 15) {
            alert("上传图片数目不可以超过15个，请重新选择");  //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        }
        else if (numUp < 15) {
            fileList = validateUp(fileList);
            for (var i = 0; i < fileList.length; i++) {
                var imgUrl = window.URL.createObjectURL(fileList[i]);
                imgArr.push(imgUrl);
                var $section = $("<section class='up-section fl loading'>");
                imgContainer.prepend($section);
                var $span = $("<span class='up-span' >");
                $span.appendTo($section);

                var $img0 = $("<img class='close-upimg'>").on("click", function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $(".works-mask").show();
                    delParent = $(this).parent();
                });
                $img0.attr("src", "img/a7.png").appendTo($section);
                var $img = $("<img class='up-img up-opcity'>");
                $img.attr("src", imgArr[i]);
                $img.appendTo($section);
                var $p = $("<p class='img-name-p'>");
                $p.html(fileList[i].name).appendTo($section);
                var $input = $("<input id='taglocation' name='taglocation' value='' type='hidden'>");
                $input.appendTo($section);
                var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
                $input2.appendTo($section);

            }
        }
        setTimeout(function () {
            $(".up-section").removeClass("loading");
            $(".up-img").removeClass("up-opcity");
        }, 450);
        numUp = imgContainer.find(".up-section").length;
        if (numUp >= 15) {
            $(this).parent().hide();
        }
    });


    $(".z_photo").delegate(".close-upimg", "click", function () {
        $(".works-mask").show();
        delParent = $(this).parent();
    });

    $(".wsdel-ok").click(function () {
        $(".works-mask").hide();
        var numUp = delParent.siblings().length;
        if (numUp < 6) {
            delParent.parent().find(".z_file").show();
        }
        var imgName = delParent[0].textContent;
        var lunboImageList = lunboImgesUrl.split(",");
        imageUrls = "";
        if (lunboImageList.length > 0) {
            for (var i = 0; i < lunboImageList.length; i++) {
                console.log(imgName);
                var lunbo = lunboImageList[i];
                if (lunbo != "" && lunbo.indexOf(imgName) == -1) {
                    imageUrls = imageUrls + lunbo + ",";
                }
            }
        }
        lunboImgesUrl = imageUrls;
        delParent.remove();
    });

    $(".wsdel-no").click(function () {
        $(".works-mask").hide();
    });

    function validateUp(files) {
        var arrFiles = [];//替换的文件数组
        for (var i = 0, file; file = files[i]; i++) {
            //获取文件上传的后缀名
            var newStr = file.name.split("").reverse().join("");
            if (newStr.split(".")[0] != null) {
                var type = newStr.split(".")[0].split("").reverse().join("");
                if (jQuery.inArray(type, defaults.fileType) > -1) {
                    // 类型符合，可以上传
                    if (file.size >= defaults.fileSize) {
                        alert(file.size);
                        alert('您这个"' + file.name + '"文件大小过大');
                    } else {
                        // 在这里需要判断当前所有文件中
                        var formData = new FormData();
                        formData.append('file', file);
                        saveLunBoPic(formData);
                        arrFiles.push(file);
                    }
                } else {
                    alert('您这个"' + file.name + '"上传类型不符合');
                }
            } else {
                alert('您这个"' + file.name + '"没有类型, 无法识别');
            }
        }
        return arrFiles;
    }
}

function submitApplyAudit(){
    if ($("#applyNo").val() == null || $("#applyNo").val() == "") {
        alert("票据编号不可为空");
        return;
    }
    if ($("#applyName").val() == null || $("#applyName").val() == "") {
        alert("票据名称不可为空");
        return;
    }
    if ($("#applyCompanyName").val() == null || $("#applyCompanyName").val() == "") {
        alert("单位名称不可为空");
        return;
    }
    if ($("#applyType").val() == 0) {
        alert("请选择审查类型");
        return;
    }
    if ($("#applyPerson").val() == null || $("#applyPerson").val() == "") {
        alert("单位联系人不可为空");
        return;
    }
    if ($("#applyAddr").val() == null || $("#applyAddr").val() == "") {
        alert("申请单位地址不可为空");
        return;
    }
    if ($("#applyPhone").val() == null || $("#applyAddr").val() == "") {
        alert("申请单位电话不可为空");
        return;
    }
    if ($("#applyStreet").val() == null || $("#applyStreet").val() == "") {
        alert("申请单位街道不可为空");
        return;
    }
    var data = {
        applyId: applyData.applyId,
        certifiedImgUrl: certifiedImgUrl
    };
    $.ajax({
        url: prefixUrl + "apply/addApplyAudit",
        type: "post",
        data: JSON.stringify(data),
        contentType: "application/json;",
        success: function (data) {
            alert(data.msg);
            modalDisplay();
            queryApplyList();
        }
    })
}

function choiceImg(type,isUpdate) {
    window.imageUrlList = imageUrlList;
    if(isUpdate == undefined){
        isUpdate = true;
    }
    window.addStatus = isUpdate;
    //window.open ('choiceImg.html?type=' + type, 'newwindow', 'height=800, width=1200, top=300, left=550, toolbar=no, menubar=no, resizable=no,location=no, status=no,titlebar=no,');
    window.open ('choiceImg.html?type=' + type);
}

function getImgUrl(imgUrls,type) {
    if(imgUrls.length > 0 && imgUrls.length != 1){
        imgUrls = imgUrls.substring(0,imgUrls.length - 1);
        var imgList = imgUrls.split(",");
        var list = [];
        for(var i=0; i<imgList.length; i++){
            var imgData = {
                "imgUrl" : imgList[i],
                "imgType": type
            };
            list[i] = imgData;
        }
        imageUrlList[type-1] = list;
    }
}

function getDetailList(imageUrlList,applyId){
    var list = [];
    var number = 0;
    for(var i=0; i<imageUrlList.length; i++){
        var typeList = imageUrlList[i];
        for(var j=0; j<typeList.length; j++){
            var data = typeList[j];
            data.applyId = applyId;
            list[number] = data;
            number++;
        }
    }
    return list;
}


function setAuditImgUrl(url){
    savePic();
}

function exportPdf(applyId,applyNo){
    $.ajax({
     url: prefixUrl + "apply/exportPdf",
     type: "post",
     data: JSON.stringify({
        applyId:applyId,
        applyNo:applyNo
     }),
     contentType: "application/json;",
     success: function (data) {
         if(data.code == 0){
            window.open(prefixUrl + 'pdf/'+ applyNo + ".pdf");
         }else{
             alert("导出PDF错误，请联系管理人员");
         }
        }
    })
}

function exportAuditPdf(applyId,imgUrl){
    $.ajax({
        url: prefixUrl + "audit/exportPdf",
        type: "post",
        data: JSON.stringify({
            applyId:applyId,
            certifiedImgUrl:imgUrl
        }),
        contentType: "application/json;",
        success: function (data) {
            if(data.code == 0){
                window.open(prefixUrl + "pdf/" + data.msg);
            }else{
                alert("导出失败，请联系管理人员");
            }
        }
    })
}

function downloadFile(url) {
    try{
        var elemIF = document.createElement("iframe");
        elemIF.src = url;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
    }catch(e){

    }
}

function browseFolder() {
    try {
        var Message = "\u8bf7\u9009\u62e9\u6587\u4ef6\u5939"; //选择框提示信息
        var Shell = new ActiveXObject("Shell.Application");
        var Folder = Shell.BrowseForFolder(0, Message, 64, 17); //起始目录为：我的电脑
        //var Folder = Shell.BrowseForFolder(0, Message, 0); //起始目录为：桌面
        if (Folder != null) {
            Folder = Folder.items(); // 返回 FolderItems 对象
            Folder = Folder.item(); // 返回 Folderitem 对象
            Folder = Folder.Path; // 返回路径
            if (Folder.charAt(Folder.length - 1) != "\\") {
                Folder = Folder + "\\";
            }
            return Folder;
        }
    }
    catch (e) {
        alert(e.message);
    }
}

function openTtile(){
    window.open("title.html");
}